<?php

namespace App\V3\V3_2_7\Services;

use App\V3\V3_2_7\Models\UserManageModel;
use Illuminate\Support\Carbon;
use function GuzzleHttp\json_decode;
use App\V3\V3_2_7\Models\AdminModel;
use App\V3\V3_2_7\Models\MaterielTypeModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\V3\V3_2_7\Models\AuditImagesModel;

class UserManageService
{
    /**
     * 标示用户
     * @param unknown $data
     * @return boolean
     */
    static public function setMarkUser($data)
    {
        $bol = false;
        $userArr = json_decode($data['user_info'],true);
        if(is_array($userArr) && count($userArr) > 0){
            $userdata = [];
            foreach ($userArr as $uVal){
                $bool = UserManageModel::where([
                    'main_id' => $uVal['main_id'],
                    'goods_id' => $uVal['goods_id'],
                    'img_path' =>$uVal['img_path']
                ])->exists();
                if(!$bool){
                    $userdata[] = [
                        'label' => 1,
                        'main_id' => $uVal['main_id'],
                        'goods_id' => $uVal['goods_id'],
                        'img_path' => $uVal['img_path'],
                        'created_at' => Carbon::now()->timestamp
                    ];
                    $imgArr[] = $uVal['img_path'];
                }
            }
            if(!empty($userdata)){
                DB::beginTransaction();
                try {
                    $bol = UserManageModel::Insert($userdata);
                    AuditImagesModel::whereIn('goods_img',$imgArr)
                    ->where([
                        'check_flag' => 0
                    ])->update(['label'=>1]);
                    DB::commit();
                    return $bol = true;
                } catch (\Exception $e) {
                    DB::rollBack();
                    Log::debug('标示用户异常：'.var_export($e->getMessage(),true));
                }
            }
        }
        return $bol;
    }

    /**
     * 取消标记用户
     * @param unknown $data
     */
    static public function del($data){
        $idArr = array_filter(
                explode(',',$data['ids']),
                function($v) { return $v !== '';
                });
        $bool = false;
        if(is_array($idArr) && count($idArr)>0){
            DB::beginTransaction();
            try {
                $imgArr = array_unique(array_column(
                UserManageModel::select('img_path')
                ->where([
                    'is_active'=>1,
                    'label'=>1,
                ])->whereIn('main_id',$idArr)
                ->get()->toArray(), 'img_path'));
                AuditImagesModel::whereIn('goods_img',$imgArr)
                ->where([
                    'check_flag' => 0
                ])->update(['label'=>0]);
                UserManageModel::whereIn('main_id',$idArr)->delete();
                DB::commit();
                return $bool = true;
            } catch (\Exception $e) {
                DB::rollBack();
                Log::debug('取消标示用户异常：'.var_export($e->getMessage(),true));
            }
        }
        return $bool;
    }
    /**
     * 查看设置标记用户列表
     * @param array $data
     */
    static public function getLabelUserList(array $data)
    {
        $query = AdminModel::select(
            'b.id',
            'a.id as main_id',
            'a.username',
            'a.nickname',
            'a.company_name',
            'a.is_active',
            'b.label',
            'b.remark',
            DB::raw('COUNT(img_path) AS Illegal_img_num')
            )->from('admin as a')
            ->leftJoin('user_manage as b', 'b.main_id', '=', 'a.id')
            ->where([
                'a.delete_flag' => 0,
                ['parent_id','=',0],
                'a.admin_role' => 2,
                'b.label' => 1,
                'a.is_active'=>1,
            ]);
            if(!empty($data['keyword'])){
                $query->where(function($query) use ($data) {
                    $query->orWhere('a.username', 'like', '%'.$data['keyword'].'%');
                    $query->orWhere('a.nickname', 'like', '%'.$data['keyword'].'%');
                    $query->orWhere('a.company_name', 'like', '%'.$data['keyword'].'%');
                });
            }
            return $query->orderBy('a.created_at','desc')->groupBy('b.main_id')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();
    }

    /**
     * 违规用户商品图片列表
     * @param unknown $data
     */
    static public function getIllegalGoodsImgList($data)
    {
        $adminInfo = AdminModel::select('id','username')
        ->where([
            'id'=>$data['id'],
            ['parent_id','=',0],
            'is_active'=>1,
            'delete_flag'=>0
        ])->first();
        if(!empty($adminInfo)){
          $list =  MaterielTypeModel::select(
              'a.id',
              'materiel_name',
              'materiel_no'
              ) ->from('materiel_type as a')
                ->leftJoin('user_manage as b','b.goods_id','=','a.id')
                ->with('illegalGoodsImgList',function($query){
                    $query->select(
                        "id",
                        "main_id",
                        "goods_id",
                        "img_path",
                        "is_active",
                        "label"
                        )->orderBy('created_at', 'DESC');
                })->where([
                    'b.main_id' => $adminInfo['id'],
                    'label' => 1,
                    'is_active' => 1
                ])->distinct()->orderBy('b.created_at', 'DESC')
                ->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();
                if(!empty($list['data'])){
                    foreach ($list['data'] as &$val){
                        $val['illegal_img_num'] = count($val['illegal_goods_img_list']);
                    }
                }
                $list['username'] = $adminInfo['username'];
                return success($list);
        }else{
            return fail('','没找到标示的用户信息');
        }
    }

    /**
     * 用户解封和禁止开头
     * @param unknown $data
     */
    static public function setUserDeblockingForbid($data)
    {
        $arr = [
            'is_active' => $data['is_active'],
            'remark' => $data['remark']??''
            ];
        DB::beginTransaction();
        try {
            AdminModel::where([
                'id' => $data['id'],
                ['parent_id','=',0],
            ])->update($arr);
            UserManageModel::where([
                'main_id' => $data['id']
            ])->update($arr);
            AuditImagesModel::where([
                'main_id' => $data['id']
            ])->update(['delete_flag'=>!empty($data['is_active'])?0:1]);
            DB::commit();
            return success();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('设置用户解封和禁止异常：'.var_export($e->getMessage(),true));
            return fail('',$e->getMessage());
        }
    }
}
